import { Service } from 'egg';
const { Op } = require("sequelize");
export default class follow extends Service {

  public async addFollow(req) {
    let state = await this.isFollow(req)
    if (state) {
      return 1
    }
    let res = await this.ctx.model.Follow.create({
      concerned: req.concerned,
      user_id: req.user_id
    })
    if (res) {
      return res
    } else {
      throw new Error()
    }
  }
  public async removeFollow(req) {
    let state = await this.isFollow(req)
    if (!state) {
      return 1
    }
    let res = await this.ctx.model.Follow.destroy({
      where: {
        concerned: req.concerned,
        user_id: req.user_id
      }
    })
    if (res) {
      return res
    } else {
      throw new Error()
    }
  }
  public async isFollow(req) {
    let res = await this.ctx.model.Follow.findOne({
      where: {
        concerned: req.concerned,
        user_id: req.user_id
      }
    })
    if (res) {
      return true
    } else {
      return false
    }
  }
  public async getFollow (req) {
    let res1 = await this.ctx.model.Follow.findAll({
      where:{
        user_id: req.user_id
      }
    })
    
    let arr: any = [];
    for(let i = 0; i< res1.length; i++) {
      arr.push(res1[i].dataValues.concerned);
    }
    let res2 = await this.ctx.model.User.findAll({
      where:{
        id:{
          [Op.in]: arr, 
        }
      }
    })
    console.log(res2);
    
    if(res2) {
      return res2
    }else{
      throw new Error()
    }
  }
}